// 定义返回类型，方便类型推导
export interface RequestResult<T = any> {
  data: T
  statusCode: number
  header: any
  cookies: string[]
  errMsg: string
}

const BASE_URL = "http://172.16.0.155:5183/api" // 全局统一的接口前缀

// 通用请求封装
export function request<T = any>(
  options: WechatMiniprogram.RequestOption
): Promise<RequestResult<T>> {
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + options.url,
      method: options.method || "GET",
      data: options.data,
      success(res) {
        const data = res.data as any;
        if (res.statusCode >= 200 && res.statusCode < 300 && (data.code === 200 || data.code === 10200)) {
          resolve(data as RequestResult<T>)
        } else {
          wx.showModal({
            title: "提示",
            content: data.message || "请求失败",
            showCancel: false
          })
          reject(data)
        }
      },
      fail(err) {
        wx.showToast({ title: "连接超时", icon: "error" })
        reject(err)
      }
    })
  })
}
